<template>
<div class="content-box">
    <e-heading>{{title}}</e-heading>
    <div class="add_class">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="课程名称：" prop="className">
          <span v-if="$route.query.isonly == 'yes'">{{$route.query.name}}</span>
          <el-select v-else v-model="form.className" value-key="id" placeholder="请选择课程" style="width: 550px;" :disabled="$route.query.isedit ? true :false" @change="handleGetschollType">
              <el-option v-for="item in train_selectclass_list" :key="item.id" :label="item.courseName" :value="item"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="班 别：" prop="type">
          <el-select v-model="form.type" value-key="key" placeholder="请选择班别" style="width:550px;" :disabled="$route.query.isedit ? true :false">
            <el-option v-for="item in train_class_type_list" :key="item.key" :label="item.value" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称：" prop="name">
          <el-input :minlength="2" :maxlength="50" v-model="form.name" style="width:550px;"></el-input>
        </el-form-item>
        <!--次课-->
        <div class="classTips">
          <el-form-item label="上课周期：" required class="set_main">
            <el-button class="set_button" type="link" @click="handlebatchShow('synthesis')" v-if="isOneEdit != 1">批量设置</el-button>
            <el-row>
              <el-col :span="24" style="margin-bottom:18px;">
                <el-checkbox-group v-model="selectWeekCode" @change="setWeekdays">
                  <el-checkbox v-for="item in weekdays" :key="item.value" :label="item.value" :disabled="isOneEdit == 1 || item.isdisable">{{item.name}}</el-checkbox>
                </el-checkbox-group>
              </el-col>
            </el-row>
          </el-form-item>
          <div class="class_time" v-if="selectWeekCode.length > 0">
            <el-row v-if="item.isShow"
              v-for="(item, index) in form.classSeting" 
              :key="index" >
              <el-col :span="2" style="margin-bottom:0;line-height:40px;text-align:center;">每{{Number(item.weekTime) | getWeekDay}}</el-col>
              <el-col :span="22" style="margin-bottom:0;" 
                v-for="(classItem, classIndex) in item.setArray" 
                :key="index+classIndex" 
                :offset="classIndex > 0 ? 2 : 0">
                <el-form-item label="" label-width="0px" :error="classItem.errorMsg">
                  <el-row>
                    <el-col :span="5">
                      <el-select v-model="classItem.campus" value-key="key" placeholder="请选择校区" style="width: 95%;" @change="hanleGetAddress(classItem.campus, index, classIndex)" :disabled="isOneEdit == 1">
                        <el-option v-for="item in train_scholl_type_list" :key="item.key" :label="item.value" :value="item"></el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="5">
                      <el-form-item>
                        <el-input :minlength="2" :maxlength="20" v-model="classItem.className" placeholder="请输入学科名称" style="width:95%;" :disabled="isOneEdit == 1"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="5">
                      <el-form-item>
                        <el-time-picker
                          is-range
                          v-model="classItem.classTime"
                          format="HH:mm"
                          :clearable="false"
                          placeholder="选择上课时间"
                          @change="handleTimeSection(classItem.classTime, index, classIndex)"
                          :disabled="isOneEdit == 1"
                          style="width:95%;">
                        </el-time-picker>
                      </el-form-item>
                    </el-col>
                    <el-col :span="5">
                      <el-select v-model="classItem.classAdd" value-key="id" placeholder="选择上课地点" style="width: 95%;" no-data-text="请先选择校区" :disabled="isOneEdit == 1" @change="handleTimeSection(classItem.classTime, index, classIndex)">
                        <el-option v-for="item in classItem.addrList" :key="item.id" :label="item.address" :value="item"></el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="1" v-if="isOneEdit != 1">
                      <el-button class="btn-icon" icon="plus" @click="handleAddClassItem(index, classIndex)" v-if="((classIndex == item.setArray.length - 1) || item.setArray.length == 1) && item.setArray.length < 4" :disabled="!(classItem.campus && classItem.className && classItem.classTime && classItem.classCoach && classItem.isError == 2)" :key="index+classIndex"></el-button>
                      <el-button class="btn-icon" icon="minus" @click="handleRemoveClassItem(index, classIndex)" v-if="(classIndex != item.setArray.length - 1) && item.setArray.length != 1"></el-button>
                    </el-col>
                    <el-col :span="18" class="col-coach">
                      <el-select v-model="classItem.classCoach" value-key="id" placeholder="请选择主教练" style="width: 100%;" 
                        @change="handleTimeSection(classItem.classTime, index, classIndex, 1)" 
                        :disabled="isOneEdit == 1">
                        <el-option v-for="item in train_teacher_list" :key="item.id" :label="item.teacherName" :value="item"
                          :disabled="checkCoachIsNotAssit(item, classItem.assistCoach)"></el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="18" class="col-coach">
                      <el-select v-model="classItem.assistCoach" value-key="id" placeholder="请选择助理教练" style="width: 100%;" multiple
                        @change="handleTimeSection(classItem.classTime, index, classIndex, 2, classItem.assistCoach)"
                        :disabled="!!isOneEdit">
                        <el-option v-for="item in train_teacher_list" :key="item.id" 
                          :label="item.teacherName" :value="item"
                          :disabled="classItem.classCoach.id === item.id || classItem.assistCoach.length >= 5 "></el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="18" class="col-coach">
                      <el-select v-model="classItem.adviser" value-key="userId" placeholder="请选择顾问" style="width: 100%;" multiple
                        :disabled="!!isOneEdit"
                        @change="handleTimeSection(classItem.classTime, index, classIndex, 3, classItem.adviser)" >
                        <el-option v-for="item in train_adviser_list" :key="item.userId" :label="item.teacherName" :value="item"
                        :disabled="classItem.adviser.length>= 3"></el-option>
                      </el-select>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
      <div class="button-box">
        <el-button @click="goBackList">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :disabled="isSubmit || isDataAtate">确 定</el-button>
      </div>
    </div>

    <!--批量设置-->
    <el-dialog
      title="批量设置"
      :visible.sync="dialogVisible"
      width="560px">
      <div class="seting_tips">
        <el-form label-width="120px">
          <el-form-item label="校 区：">
            <el-select v-model="form.batchSet.campus" value-key="key" placeholder="请选择校区" style="width: 85%;" @change="hanleGetAllAddress(form.batchSet.campus)">
              <el-option v-for="item in train_scholl_type_list" :key="item.key" :label="item.value" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学科名称：">
            <el-input :minlength="2" :maxlength="20" v-model="form.batchSet.className" placeholder="请输入学科名称" style="width:85%;"></el-input>
          </el-form-item>
          <el-form-item label="上课时间：">
            <el-time-picker
              is-range
              :clearable="false"
              format="HH:mm"
              v-model="form.batchSet.classTime"
              placeholder="选择上课时间" style="width: 85%;">
            </el-time-picker>
          </el-form-item>
          <el-form-item label="上课地点：">
            <el-select v-model="form.batchSet.classAdd" value-key="id" placeholder="选择上课地点" no-data-text="请先选择校区" style="width: 85%;">
              <el-option v-for="item in addressList" :key="item.id" :label="item.address" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="教练团队：">
            <el-select v-model="form.batchSet.classCoach" value-key="id" placeholder="请选择主教练" class="batch-set">
              <el-option v-for="item in train_teacher_list" :key="item.id" :label="item.teacherName" :value="item"
                :disabled="checkCoachIsNotAssit(item, form.batchSet.assistCoach)"></el-option>
            </el-select>
            <el-select v-model="form.batchSet.assistCoach" value-key="id" placeholder="请选择助理教练" class="batch-set" multiple>
              <el-option v-for="item in train_teacher_list" :key="item.id" :label="item.teacherName" :value="item"
                :disabled="form.batchSet.classCoach.id == item.id || form.batchSet.assistCoach.length >= 5"></el-option>
            </el-select>
            <el-select v-model="form.batchSet.adviser" value-key="userId" placeholder="请选择顾问" class="batch-set" multiple>
              <el-option v-for="item in train_adviser_list" :key="item.userId" :label="item.teacherName" :value="item"
                :disabled="form.batchSet.adviser.length >= 3"></el-option>
            </el-select>
          </el-form-item>
        </el-form> 
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleReset">重 置</el-button>
        <el-button type="primary" @click="handleBatchSet">确 定</el-button>
      </span>
    </el-dialog>
</div>
</template>
<script>
import trainApi from 'api/train'
import { mapGetters } from 'vuex'
import { parseTime } from 'utils'
export default {
  computed: {
    ...mapGetters({
      train_teacher_list: 'train_teacher_list',
      train_selectclass_list: 'train_selectclass_list',
      train_scholl_type_list: 'train_scholl_type_list',
      train_class_type_list: 'train_class_type_list',
      train_teacher_info: 'train_teacher_info',
      train_adviser_list: 'train_adviser_list'
    })
  },
  beforeCreate () {
    this.$store.dispatch('train_teacher_list')
    this.$store.dispatch('train_selectclass_list')
    this.$store.dispatch('train_adviser_list')
  },
  created () {
    if (this.$route.query.isedit === 'edit') {
      this.isEditone = true
      trainApi.classEdit({
        id: this.$route.query.id
      }).then((res) => {
        this.dedaultData = res.data
        if (res.data.listCourseCycle && res.data.listCourseCycle.length === 0) {
          this.isOneEdit = 0
        } else {
          this.isOneEdit = 1
        }
        this.setDefaultData()
      })
      let getWeeks = this.$route.query.weekdays ? this.$route.query.weekdays.split(',') : ''
      if (getWeeks) {
        for (let days of getWeeks) {
          this.selectWeekCode.push(Number(days))
          this.getWeeks.push(Number(days))
        }
      }
    }
  },
  mounted () {
    if (this.$route.query.thisid) {
      this.form.className = {id: Number(this.$route.query.thisid), courseName: ''}
      let scope = this
      setTimeout(function () {
        for (let i = 0; i < scope.train_selectclass_list.length; i++) { // 取的匹配课程上课时间范围
          if (scope.train_selectclass_list[i].id === Number(scope.$route.query.thisid)) {
            scope.form.className.startClassTime = scope.train_selectclass_list[i].startClassTime
            scope.form.className.endClassTime = scope.train_selectclass_list[i].endClassTime
            scope.form.className.properties = scope.train_selectclass_list[i].properties
          }
        }
        scope.handleGetschollType()
      }, 500)
    }
    for (let sitem of [1, 2, 3, 4, 5, 6, 7]) {
      this.form.classSeting.push({
        weekTime: sitem,
        weekCode: sitem,
        isShow: false,
        setArray: [
          {
            campus: '',
            className: '',
            classTime: '',
            classAdd: '',
            classCoach: '', // 主教练
            assistCoach: [], // 助理教练
            adviser: [], // 顾问
            addrList: [],
            errorMsg: '',
            errorCoach: [],
            isError: 2,
            errorRoleType: []
          }
        ]
      })
    }
  },
  data () {
    return {
      title: '班级信息',
      dedaultData: {},
      schoolList: [],
      gradeList: [],
      getWeeks: [],
      dialogVisible: false,
      isSynthesis: false,
      isOneEdit: 0,
      roleType: localStorage.getItem('role_type'),
      weekdays: [
        {name: '每周一', value: 1, isdisable: false},
        {name: '每周二', value: 2, isdisable: false},
        {name: '每周三', value: 3, isdisable: false},
        {name: '每周四', value: 4, isdisable: false},
        {name: '每周五', value: 5, isdisable: false},
        {name: '每周六', value: 6, isdisable: false},
        {name: '每周日', value: 7, isdisable: false}
      ],
      selectWeekCode: [],
      isEditone: false,
      isClassSet: [],
      isError: false,
      teacherRoleType: 1, // 1：助教，2：顾问
      form: {
        className: '',
        type: '',
        name: '',
        coach: '',
        classSeting: [],
        batchSet: {
          campus: '',
          className: '',
          classTime: '',
          classAdd: '',
          classCoach: '', // 主教练
          assistCoach: [], // 助理教练
          adviser: [], // 顾问
          addrList: []
        }
      },
      subList: [],
      addressList: [],
      isDataAtate: false,
      isSubmit: true,
      coachNotDuplicate: false, // 主教练上课时间未重复
      assistCoachNotDuplicate: false, // 助理教练上课时间未重复，
      adviserNotDuplicate: false,
      rules: {
        className: [
          { type: 'object', required: true, message: '请选择课程', trigger: 'change' }
        ],
        type: [
          { type: 'object', required: true, message: '请选择班别', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入班级名称', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'form.classSeting': {
      handler () {
        // this.getsubData()
      },
      deep: true
    }
  },
  methods: {
    handlebatchShow (type) {
      if (this.selectWeekCode.length === 0) {
        this.$alert('请先勾选上课周期', '温馨提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
      } else {
        if (type === 'synthesis') {
          this.isSynthesis = true
        } else {
          this.isSynthesis = false
        }
        this.dialogVisible = true
      }
    },
    goBackList () {
      this.$router.push({path: '/training/class'})
    },
    handleCheckTeacher (index, classIndex, roleType = 1) { // 次课教练校验
      if (this.form.classSeting[index].setArray[classIndex].classTime[0]) {
        if (roleType === 1) {
          if (this.form.classSeting[index].setArray[classIndex].classCoach !== '') {
            this.checkTeacher(this.form.classSeting[index].setArray[classIndex].classCoach.id, index, classIndex)
          }
        } else if (roleType === 2) { // 助教
          if (this.form.classSeting[index].setArray[classIndex].assistCoach.length) {
            let teacherIdList = this.form.classSeting[index].setArray[classIndex].assistCoach.map(item => item.id)
            this.checkTeacher(teacherIdList, index, classIndex, 2)
          } else { // 没有助教
            let $item = this.form.classSeting[index].setArray[classIndex]
            let $errorCoach = this.getValidErrorCoach($item)
            $item.errorMsg = $errorCoach.length ? `${$errorCoach.map(item => item.teacherName).join('，')}教练在此时间段已有课程，请重新设置` : ''
            $item.errorCoach = $errorCoach
          }
        } else if (roleType === 3) { // 顾问
          if (this.form.classSeting[index].setArray[classIndex].adviser.length) {
            let teacherIdList = this.form.classSeting[index].setArray[classIndex].adviser.map(item => item.userId)
            this.checkTeacher(teacherIdList, index, classIndex, 3)
          } else { // 没有顾问
            let $item = this.form.classSeting[index].setArray[classIndex]
            let $errorCoach = this.getValidErrorCoach($item)
            $item.errorMsg = $errorCoach.length ? `${$errorCoach.map(item => item.teacherName).join('，')}教练在此时间段已有课程，请重新设置` : ''
            $item.errorCoach = $errorCoach
          }
        }
      }
    },
    getValidErrorCoach ($item) {
      let ids = []
      let result = []
      $item.errorCoach = $item.errorCoach || []
      let assistCoachIds = $item.assistCoach.map(item => {
        if (item) {
          return item.id
        }
      })
      let adviserCoachIds = $item.adviser.map(item => {
        if (item) {
          return item.userId
        }
      })
      result = $item.errorCoach.filter(item => {
        return item.id === ($item.classCoach || {}).id || assistCoachIds.indexOf(item.id) > -1 || adviserCoachIds.indexOf(item.id) > -1
      })
      return result.filter(item => { // 去重
        if (ids.indexOf(item.id) === -1) {
          ids.push(item.id)
          return true
        } else {
          return false
        }
      })
    },
    checkTeacher (teacherid, index, classIndex, roleType = 1) { // 教练校验请求
      if (this.form.classSeting[index].setArray[classIndex].classTime[0] && this.isError) {
        if (typeof teacherid === 'number') {
          trainApi.checkTeacher({
            courseType: this.$route.query.courseType,
            schoolId: this.form.classSeting[index].setArray[classIndex].campus.key,
            cycleId: this.form.classSeting[index].setArray[classIndex].id,
            courseId: this.form.className.id,
            weekCode: this.form.classSeting[index].weekCode,
            addressId: this.form.classSeting[index].setArray[classIndex].classAdd.id,
            teacherId: teacherid,
            classBeginTimeStr: parseTime(this.form.classSeting[index].setArray[classIndex].classTime[0], '{h}:{i}'),
            classEndTimeStr: parseTime(this.form.classSeting[index].setArray[classIndex].classTime[1], '{h}:{i}')
          }).then((res) => {
            let $item = this.form.classSeting[index].setArray[classIndex]
            let $errorCoach = this.getValidErrorCoach($item)
            if (res.data) {
              let teacher = this.train_teacher_list.filter(item => {
                return item.id === teacherid
              })[0]
              $errorCoach.every(item => item.id !== teacherid) && $errorCoach.unshift({
                ...teacher
              })
            }
            $item.errorMsg = $errorCoach.length ? `${$errorCoach.map(item => item.teacherName).join('，')}教练在此时间段已有课程，请重新设置` : ''
            $item.errorCoach = $errorCoach
          })
        } else {
          if (roleType === 2 || roleType === 3) { // 2:助教，3：顾问
            let self = this
            let $item = self.form.classSeting[index].setArray[classIndex]
            let $errorCoach = this.getValidErrorCoach($item)
            teacherid.forEach(assist => {
              let checkObj = {
                courseType: this.$route.query.courseType,
                schoolId: this.form.classSeting[index].setArray[classIndex].campus.key,
                cycleId: this.form.classSeting[index].setArray[classIndex].id,
                courseId: this.form.className.id,
                weekCode: this.form.classSeting[index].weekCode,
                userType: roleType,
                addressId: this.form.classSeting[index].setArray[classIndex].classAdd.id,
                classBeginTimeStr: parseTime(this.form.classSeting[index].setArray[classIndex].classTime[0], '{h}:{i}'),
                classEndTimeStr: parseTime(this.form.classSeting[index].setArray[classIndex].classTime[1], '{h}:{i}')
              }
              if (roleType === 3) {
                checkObj.userId = assist
                checkObj.userType = 2
              } else {
                checkObj.teacherId = assist
                checkObj.userType = 1
              }
              ((data) => {
                trainApi.checkTeacher(data).then((res) => {
                  if (res.data) {
                    if (data.userType === 1) {
                      self.train_teacher_list.forEach(item => {
                        if (item.id === data.teacherId && $errorCoach.every(_item => _item.id !== data.teacherId)) {
                          $errorCoach.push({
                            teacherName: item.teacherName,
                            id: item.id
                          })
                        }
                      })
                    } else {
                      self.train_adviser_list.forEach(item => {
                        if (item.userId === data.userId && $errorCoach.every(_item => _item.id !== data.userId)) {
                          $errorCoach.push({
                            teacherName: item.teacherName,
                            id: item.userId
                          })
                        }
                      })
                    }
                  }
                  $item.errorMsg = $errorCoach.length ? `${$errorCoach.map(item => item.teacherName).join('，')}教练在此时间段已有课程，请重新设置` : ''
                  $item.errorCoach = $errorCoach
                })
              })(checkObj)
            })
          }
        }
      }
    },
    setDefaultData () { // 编辑时设置初始数据
      this.form.className = {id: this.dedaultData.courseId, courseName: ''}
      this.form.name = this.dedaultData.name
    },
    setWeekdays () { // 勾选上课周期
      this.selectWeekCode = this.selectWeekCode.sort((a, b) => {
        return a - b
      })
      this.setStratClassList()
    },
    handleGetschollType () { // 根据课程ID获取校区班别数据
      this.form.type = ''
      if (this.form.className) {
        this.$store.dispatch('train_scholl_type_list', {courseId: this.form.className.id})
        this.$store.dispatch('train_class_type_list', {courseId: this.form.className.id})
        this.setStratClassList()
        if (this.$route.query.isedit === 'edit') { // 编辑时教师数据
          for (let i of this.train_selectclass_list) {
            if (i.id === this.dedaultData.courseId) {
              this.form.className.properties = i.properties
            }
          }
          if (this.form.className.properties === 0) {
            this.form.coach = {id: this.dedaultData.listCourseCycle[0].teacherId, value: ''}
          }
          this.form.type = {key: this.dedaultData.classesId, value: ''}
        }
        if (this.roleType === '99' && this.$route.query.isedit !== 'edit') { // 教练员默认设置自己
          this.form.coach = {id: this.train_teacher_info.id, teacherName: this.train_teacher_info.name}
          this.form.batchSet.classCoach = {id: this.train_teacher_info.id, teacherName: this.train_teacher_info.name}
          let classSeting = this.form.classSeting
          for (let item of classSeting) {
            let setArray = item.setArray
            for (let smItem of setArray) {
              smItem.classCoach = {id: this.train_teacher_info.id, teacherName: this.train_teacher_info.name}
            }
          }
        }
      }
    },
    setStratClassList () { // 设置默认上课周期数据
      if (this.form.className) {
        for (let item of this.train_selectclass_list) {
          if (item.id === this.form.className.id) {
            let codeArr = this.selectWeekCode
            for (let hitem of this.form.classSeting) {
              this.$set(hitem, 'isShow', false)
              for (let sitem of codeArr) {
                if (hitem.weekCode === sitem) {
                  this.$set(hitem, 'isShow', true)
                }
              }
            }
          }
        }
        if (this.$route.query.isedit === 'edit' && this.isEditone) { // 编辑设置初始值
          let classTimelist = this.dedaultData.listCourseCycle
          for (let hitem of this.form.classSeting) {
            if (this.getWeeks.includes(hitem.weekCode)) {
              hitem.setArray = []
            }
            setTimeout(() => {
              for (let i = 0; i < classTimelist.length; i++) { // 编辑时设置初始上课周期数据
                if (classTimelist[i] && classTimelist[i].weekCode === Number(hitem.weekCode)) {
                  classTimelist[i].isShow = true
                  trainApi.getAddress({
                    schoolId: classTimelist[i].schoolId
                  }).then((res) => {
                    let adviserList = classTimelist[i].listTeachers.map(item => {
                      if (item.roleType === 2) {
                        return ({
                          id: item.teacherId,
                          teacherName: item.teacherName,
                          userId: item.userId
                        })
                      }
                    })
                    let assistCoach = classTimelist[i].listTeachers.map(item => {
                      if (item.roleType === 1) {
                        return ({
                          id: item.teacherId,
                          teacherName: item.teacherName,
                          userId: item.userId
                        })
                      }
                    })
                    hitem.setArray.push({
                      campus: {key: classTimelist[i].schoolId, value: ''},
                      className: classTimelist[i].subjectName,
                      classTime: [new Date(classTimelist[i].beginTime), new Date(classTimelist[i].endTime)],
                      classAdd: {id: classTimelist[i].addressId, address: ''},
                      classCoach: {id: classTimelist[i].teacherId, teacherName: ''},
                      adviser: adviserList,
                      assistCoach: assistCoach,
                      addrList: res.data,
                      errorMsg: '',
                      errorCoach: [],
                      isError: 2,
                      id: classTimelist[i].id,
                      errorRoleType: []
                    })
                  })
                }
              }
            }, 300)
          }
        }
      }
    },
    hanleGetAddress (value, index, classIndex) { // 根据校区获取上课地址
      if (value) {
        trainApi.getAddress({
          schoolId: value.key
        }).then((res) => {
          this.form.classSeting[index].setArray[classIndex].addrList = res.data
          this.form.classSeting[index].setArray[classIndex].classAdd = ''
        })
      }
    },
    hanleGetAllAddress (value) { // 批量根据校区获取上课地址
      if (value) {
        trainApi.getAddress({
          schoolId: value.key
        }).then((res) => {
          this.addressList = res.data
          this.form.batchSet.classAdd = ''
        })
      }
    },
    checkTeaching (index, classIndex) { // 教练上课时间校验
      this.handleCheckTeacher(index, classIndex)
    },
    /*
      val: 时间
      index: 星期几
      classIndex: 第几节课
      roletype : 区分教练，主教练，顾问
    */
    handleTimeSection (val, index, classIndex, roleType, checkTeachers) { // 时间区间限制08:00-22:00&&一天之内课时不能重复
      if ((roleType === 2 || roleType === 3) && !checkTeachers.length) {
        let lesson = this.form.classSeting[index].setArray[classIndex]
        let errIndex = lesson.errorRoleType.indexOf(roleType)
        lesson.errorRoleType.splice(errIndex, 1)
        if (!lesson.errorRoleType.length) {
          this.isSubmit = false
          lesson.errorMsg = ''
        } else {
          if (lesson.errorRoleType.includes(1)) {
            lesson.errorMsg = `此时间段该教练已有课程，请重新设置`
          } else if (lesson.errorRoleType.includes(2)) {
            lesson.errorMsg = `此时间段该助理教练已有课程，请重新设置`
          } else if (lesson.errorRoleType.includes(3)) {
            lesson.errorMsg = `此时间段该顾问已有课程，请重新设置`
          }
        }
        if (lesson.errorRoleType.includes(1)) {
        } else if (!(lesson.errorRoleType.includes(2) && lesson.errorRoleType.includes(3))) {
          // this.isSubmit = false
          // return
        } else {
          // return
        }
      }
      if (val && (parseTime(val[0], '{h}:{i}') < '08:00' || parseTime(val[1], '{h}:{i}') > '22:00')) {
        this.form.classSeting[index].setArray[classIndex].errorMsg = '上下课时间范围为08:00-22:00'
        this.isSubmit = true
        this.isError = false
        this.form.classSeting[index].setArray[classIndex].classTime = []
      } else if (val && val[0]) {
        this.form.classSeting[index].setArray[classIndex].errorMsg = ''
        this.isSubmit = false
        this.isError = true
        if (val[1].getTime() - val[0].getTime() < 600000) {
          this.form.classSeting[index].setArray[classIndex].errorMsg = '上下课时间范围最小间隔为10分钟'
          this.isSubmit = true
          this.isError = false
        } else {
          this.form.classSeting[index].setArray[classIndex].errorMsg = ''
          this.isSubmit = false
          this.isError = true
          let isError = [] // 校验上课时间重复
          let isErrorTeacher = [] // 同一时间校验教练不能相同
          let errorRoleType
          this.form.classSeting[index].setArray[classIndex].errorRoleType = this.form.classSeting[index].setArray[classIndex].errorRoleType || []
          for (let i = 0; i < this.form.classSeting[index].setArray.length; i++) {
            let item = this.form.classSeting[index].setArray[i]
            let classLength = this.form.classSeting[index].setArray.length
            if (classLength > 1) {
              if (classIndex !== i) {
                if (!(parseTime(val[0], '{h}:{i}') > parseTime(item.classTime[1], '{h}:{i}') || parseTime(val[1], '{h}:{i}') < parseTime(item.classTime[0], '{h}:{i}'))) {
                  isError.push(false)
                  if (this.form.classSeting[index].setArray[classIndex].classCoach === item.classCoach) { // 时间相同，教练不能相同
                    if (this.form.classSeting[index].setArray[classIndex].errorRoleType.indexOf(1) === -1) {
                      this.form.classSeting[index].setArray[classIndex].errorRoleType.push(1)
                    }
                    errorRoleType = '主教练'
                    isErrorTeacher.push(false)
                  }
                  // debugger
                  let assistCoach = this.form.classSeting[index].setArray[classIndex].assistCoach
                  let assistCoach2 = item.assistCoach
                  assistCoach.forEach((assist) => {
                    assistCoach2.forEach((assist2) => {
                      if (assist.id === assist2.id) {
                        if (this.form.classSeting[index].setArray[classIndex].errorRoleType.indexOf(2) === -1) {
                          this.form.classSeting[index].setArray[classIndex].errorRoleType.push(2)
                        }
                        errorRoleType = '助理教练'
                        isErrorTeacher.push(false)
                      }
                    })
                  })
                  let adviser = this.form.classSeting[index].setArray[classIndex].adviser
                  let adviser2 = item.adviser
                  adviser.forEach((ad) => {
                    adviser2.forEach(ad2 => {
                      if (ad.userId === ad2.userId) {
                        if (this.form.classSeting[index].setArray[classIndex].errorRoleType.indexOf(3) === -1) {
                          this.form.classSeting[index].setArray[classIndex].errorRoleType.push(3)
                        }
                        errorRoleType = '顾问'
                        isErrorTeacher.push(false)
                      }
                    })
                  })
                }
              }
            }
          }
          if (isError.includes(false)) {
            if (isErrorTeacher.includes(false)) {
              this.form.classSeting[index].setArray[classIndex].errorMsg = `此时间段该${errorRoleType}已有课程，请重新设置`
              this.isError = false
              this.isSubmit = true
              this.$set(this.form.classSeting[index].setArray[classIndex], 'isError', 1)
            } else {
              this.handleCheckTeacher(index, classIndex, roleType)
            }
          } else {
            this.handleCheckTeacher(index, classIndex, roleType)
          }
        }
      }
    },
    getsubData () { // 转换提交数据
      let classSeting = this.form.classSeting
      this.subList = []
      let arrSub = []
      for (let item of classSeting) {
        if (item.isShow !== false) {
          let setArray = item.setArray
          for (let smItem of setArray) {
            if (smItem.campus && smItem.classCoach && smItem.className && smItem.classTime) { // 校验周期必填除导航可地点外
              arrSub.push(true)
            } else {
              arrSub.push(false)
            }
            let listTeachers = []
            smItem.assistCoach.forEach(item => { // 助教
              if (item) {
                listTeachers.push({
                  roleType: 1,
                  teacherId: item.id
                })
              }
            })
            smItem.adviser.forEach(item => { // 顾问
              if (item) {
                listTeachers.push({
                  roleType: 2,
                  userId: item.userId
                })
              }
            })
            if (smItem.className || smItem.classAdd) {
              this.subList.push({
                schoolId: smItem.campus ? smItem.campus.key : '',
                subjectName: smItem.className,
                weekCode: item.weekCode,
                beginTime: new Date(smItem.classTime[0]).getTime(),
                endTime: new Date(smItem.classTime[1]).getTime(),
                addressId: smItem.classAdd ? smItem.classAdd.id : '',
                teacherId: smItem.classCoach ? smItem.classCoach.id : '',
                listTeachers: listTeachers
              })
            }
          }
        }
      }
      if (arrSub.length === 0 || arrSub.includes(false)) {
        this.isDataAtate = true
      } else {
        this.isDataAtate = false
      }
    },
    handleSubmit () { // 提交信息
      this.$refs['form'].validate((valid) => {
        if (this.isClassSet.includes(false)) {
          this.$message({
            type: 'warning',
            message: '上课周期不能为空'
          })
        } else {
          if (valid) {
            this.getsubData()
            let params = {
              courseType: this.$route.query.courseType,
              courseId: this.form.className.id,
              classesId: this.form.type.key,
              name: this.form.name,
              listCourseCycle: this.subList
            }
            let methodType = this.$route.query.isedit === 'edit' ? 'put' : 'post'
            if (this.$route.query.isedit === 'edit') {
              params.id = this.$route.query.id
            }
            trainApi.addClassRoom(JSON.stringify(params), methodType).then((res) => {
              this.$router.push({path: '/training/class'})
            })
          } else {
            return false
          }
        }
      })
    },
    handleAddClassItem (index, classIndex) { // 增加上课时间
      let defaultCoach = ''
      if (this.roleType === '99') {
        defaultCoach = {id: this.train_teacher_info.id, teacherName: this.train_teacher_info.name}
      }
      this.$set(this.form.classSeting[index].setArray, classIndex + 1, {
        campus: '',
        className: '',
        classTime: '',
        classAdd: '',
        classCoach: defaultCoach,
        assistCoach: [],
        adviser: [],
        addrList: [],
        errorMsg: '',
        errorCoach: [],
        isError: 2
      })
    },
    handleRemoveClassItem (index, classIndex) { // 减少上课时间
      this.form.classSeting[index].setArray.splice(classIndex, 1)
      let isError = []
      for (let i = 0; i < this.form.classSeting[index].setArray.length; i++) {
        let item = this.form.classSeting[index].setArray[i]
        if (classIndex !== i) {
          if (!(this.form.classSeting[index].setArray[classIndex].classTime[0].getTime() > item.classTime[1].getTime() || this.form.classSeting[index].setArray[classIndex].classTime[1].getTime() < item.classTime[0].getTime())) {
            isError.push(false)
          }
        }
      }
      if (isError.includes(false)) {
        this.form.classSeting[index].setArray[classIndex].errorMsg = '上课时间重复'
        this.isError = false
        this.$set(this.form.classSeting[index].setArray[classIndex], 'isError', 1)
      } else {
        this.form.classSeting[index].setArray[classIndex].errorMsg = ''
        this.isError = true
        this.checkTeaching(index, classIndex)
        this.$set(this.form.classSeting[index].setArray[classIndex], 'isError', 2)
      }
    },
    handleBatchSet (type) { // 批量设置上课时间
      let classSeting = this.form.classSeting
      let batchSeting = this.form.batchSet
      for (let item of classSeting) {
        let setArray = item.setArray
        for (let smItem of setArray) {
          smItem.addrList = this.addressList
          smItem.campus = batchSeting.campus
          smItem.className = batchSeting.className
          smItem.classTime = batchSeting.classTime
          smItem.assistCoach = batchSeting.assistCoach.concat()
          smItem.adviser = batchSeting.adviser.concat()
          smItem.classCoach = batchSeting.classCoach
          setTimeout(() => {
            smItem.classAdd = batchSeting.classAdd
          }, 500)
          if (type === 'reset') {
            smItem.errorMsg = ''
          }
        }
      }
      let total = classSeting.filter(item => item.isShow)
      total.forEach((day, weekday) => {
        let classItem = day.setArray
        classItem.forEach((cls, idx) => {
          this.handleTimeSection(cls.classTime, weekday, idx, 1)
          this.handleTimeSection(cls.classTime, weekday, idx, 2, cls.assistCoach)
          this.handleTimeSection(cls.classTime, weekday, idx, 3, cls.adviser)
        })
      })
      this.dialogVisible = false
    },
    handleReset () { // 批量重置时间
      let defaultCoach = ''
      if (this.roleType === '99') {
        defaultCoach = {id: this.train_teacher_info.id, teacherName: this.train_teacher_info.name}
      }
      this.form.batchSet = {
        campus: '',
        className: '',
        classTime: '',
        classAdd: '',
        classCoach: defaultCoach,
        assistCoach: [],
        adviser: [],
        errorCoach: []
      }
      this.handleBatchSet('reset')
      this.dialogVisible = false
    },
    // 校验主教练和助教不能重复
    checkCoachIsNotAssit (coach, assistList) {
      let isDuplicate = false
      for (let i = 0, l = assistList.length; i < l; i++) {
        if (assistList[i] && assistList[i].id === coach.id) {
          isDuplicate = true
        }
      }
      return isDuplicate
    }
  }
}
</script>
<style lang="scss">
.add_class{
  margin-top:30px;
  .set_main{
    position: relative;
    .set_button{
      position: absolute;
      left:-80px;
      top:38px;
    }
  }
  .set_all{
    margin-bottom:0;
    text-align:center;
    color:#486a67;
    text-align: left;
  }
  .el-select{
    vertical-align: top;
  }
  .el-button.is-disabled, .el-button.is-disabled:hover{
    .el-icon-plus{
      color:#e5e5e5;
    }
  }
  .el-button--text{
    color:#2a82ee;
  }
  .el-button.is-disabled, .el-button.is-disabled:hover{
    color:#d0cfcf;
  }
  .el-button--primary.is-disabled,
  .el-button--primary.is-disabled:hover,
  .el-button--primary.is-disabled:focus{
    color:#fff;
  }
  .class_time{
    margin:20px;
    background: #fafafa;
    padding:20px 0 0 5px;
  }
}
.col-coach{
  margin-top:18px;
}
.batch-set{
  width: 315px!important;
  margin-bottom: 15px;
}
</style>
